package com.tzy.for10evalue.common.excel;

import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.CellData;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.property.ExcelContentProperty;
import com.alibaba.excel.util.DateUtils;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * easyexcel 导出 自定义转换器
 * @author tzy
 * @date 2022/9/21 10:44
 */
public class DateConverter implements Converter<Date> {


    private static  final String PATTERN_YYYY_MM_DD = "yyyy-MM-dd";


    @Override
    public Class supportJavaTypeKey() {
       return Date.class;
    }

    @Override
    public CellDataTypeEnum supportExcelTypeKey() {
        return CellDataTypeEnum.STRING;
    }

    @Override
    public Date convertToJavaData(CellData cellData, ExcelContentProperty excelContentProperty, GlobalConfiguration globalConfiguration) throws Exception {
       return excelContentProperty != null && excelContentProperty.getDateTimeFormatProperty() != null ? DateUtils.parseDate(cellData.getStringValue(), excelContentProperty.getDateTimeFormatProperty().getFormat()) : DateUtils.parseDate(cellData.getStringValue(), (String)null);
    }

    @Override
    public CellData convertToExcelData(Date date, ExcelContentProperty excelContentProperty, GlobalConfiguration globalConfiguration) throws Exception {
        SimpleDateFormat sdf = new SimpleDateFormat(PATTERN_YYYY_MM_DD);
        String dateValue = sdf.format(date);
        return new CellData<>(dateValue);
    }
}
